package com.banzhi.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.GoodsBean;
import com.banzhi.shop.entity.HomeFrg.HomeFrg_Data;
import com.banzhi.shop.entity.HomeFrg.goods_data;
import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.fragment.HomeShopFrg;
import com.banzhi.shop.model.CallBack.HomeFrgModelCallBack;
import com.banzhi.shop.model.CallBack.ISCanByCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;
import com.banzhi.shop.model.IHomeFrgModel;
import com.banzhi.shop.model.IIsCanByModel;
import com.banzhi.shop.model.Impl.HomeFrgModelImpl;
import com.banzhi.shop.model.Impl.IsCanByImpl;
import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.CustomToast;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 今日特卖
 */
public class GroupDayActivity extends BaseActivity implements HomeFrgModelCallBack, SwipeRefreshLayout.OnRefreshListener, ISCanByCallBack, WXshareCallBack {
    private ImageView mImagBack;
    private TextView mTitle;
    private SwipeRefreshLayout mRefreshLayout; // 下拉
    private RelativeLayout mEntityData; // 空数据布局
    private RecyclerView recyclerView; // 控件
    //    private RecyclerViewAda adapter;
    private IHomeFrgModel model;
    /**
     * 页数，一页10个数据
     */
    private int page = 1;
    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private WXshareModel wxmodel;
    private int positon;
    /**
     * 时候以添加到店铺的状态值
     */
    private String icon;

    private LinearLayoutManager layoutManager;
    private List<GoodsBean> res = new ArrayList<>();
    private CommonHeadAdapter<GoodsBean> adapter;
    private IIsCanByModel canByModel;
    private int position;
    /**
     * 选项卡的ID   用来展现不同的界面
     */
    private String id;

    public static void showDayActivity(Context context, String id, String title) {
        Intent intent = new Intent(context, GroupDayActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_day);
        initView();
        initListener();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            id = intent.getStringExtra("id");
            mTitle.setText(intent.getStringExtra("title"));
        } else {
            finish();
        }
        model = new HomeFrgModelImpl();
        model.getDataforID(id, page + "", this);
        wxmodel = new WXshareImpl();
        canByModel = new IsCanByImpl();
    }

    private void initListener() {
        mImagBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mRefreshLayout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                model.getDataforID(id, page + "", GroupDayActivity.this);
            }
        });
    }

    private void initView() {
        Translucent.setTranslucent(this);
        mImagBack = (ImageView) findViewById(R.id.iv_back);
        mTitle = (TextView) findViewById(R.id.tv_title);
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srlayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mEntityData = (RelativeLayout) findViewById(R.id.rl_nodata);
        mRefreshLayout.setColorSchemeResources(R.color.themeColor);
        mRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
    }

    /**
     * 轮播图片的集合
     */
    private List<String> imgesUrl = new ArrayList<>();

    /**
     * @param object 获取商品信息成功
     */
    @Override
    public void getDataSuccess(Object object) {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        HomeFrg_Data data = (HomeFrg_Data) object;
        if (page == 1) {
            res.clear();
            //获取图片资源并加载图片
            imgesUrl.clear();
            if (data.getAdvs() != null) {
                for (int i = 0; i < data.getAdvs().size(); i++) {
                    imgesUrl.add(data.getAdvs().get(i).getThumb());
                }
            }
        } else {
            if (data.getGoods().size() == 0) {
                return;
            }
        }
        res.addAll(data.getGoods());
        if(res.size() == 0) {
            mEntityData.setVisibility(View.VISIBLE);
        }else {
            mEntityData.setVisibility(View.GONE);
        }
        if (adapter == null) {
            adapter = new CommonHeadAdapter<GoodsBean>(this, R.layout.recycleview_items2, res) {
                @Override
                public void convert(ViewHolder holder, final GoodsBean data, final int position) {
                    if ("1".equals(MyApp.loginMessage.getString("isagent",""))) {
                        holder.getImageView(R.id.iv_add_dianpu).setVisibility(View.VISIBLE);
                        holder.getImageView(R.id.iv_fenxiang).setVisibility(View.VISIBLE);
                        holder.getView(R.id.ll_lirun).setVisibility(View.VISIBLE);
                    }else {
                        holder.getImageView(R.id.iv_add_dianpu).setVisibility(View.INVISIBLE);
                        holder.getImageView(R.id.iv_fenxiang).setVisibility(View.INVISIBLE);
                        holder.getView(R.id.ll_lirun).setVisibility(View.GONE);
                    }
                    //利润
                    if (ASUtils.isCanUse(data.getProfit())) {
                        holder.setText(R.id.tv_liyun, data.getProfit());
                    }
                    //   holder.setText(R.id.tv_lijian2,data.getProfit());
                    //在售人数
                    holder.setText(R.id.tv_Peoplenum, data.getSharebtn());
                    //是不是加入店铺了
                    if ("0".equals(data.getIcon())) {
                        holder.getImageView(R.id.iv_add_dianpu).setImageResource(R.mipmap.jian1);

                        holder.getImageView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                                model.deleteGoods(data.getId(), null, GroupDayActivity.this);
                                GroupDayActivity.this.positon = position;
                                GroupDayActivity.this.icon = data.getIcon();
                            }
                        });
                    } else if ("1".equals(data.getIcon())) {
                        holder.getImageView(R.id.iv_add_dianpu).setImageResource(R.mipmap.jia1);
                        holder.getImageView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                                model.AddDianpu(data.getId(), GroupDayActivity.this);
                                GroupDayActivity.this.positon = position;
                                GroupDayActivity.this.icon = data.getIcon();
                            }
                        });
                    }
                    //详情
                    holder.getImageView(R.id.iv_add_image).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Intent intent = new Intent(GroupDayActivity.this, CommodityDetailsActivity.class);
                            intent.putExtra("id", data.getId());
                            intent.putExtra("type", "1");
                            startActivity(intent);
                        }
                    });
                    //分享
                    holder.getImageView(R.id.iv_fenxiang).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            wxURL = null;
                            showSharePopupwindow(data);
                            GroupDayActivity.this.positon = position;


                        }
                    });
                    //标题
                    holder.setText(R.id.tv_home_content, data.getTitle());
                    //库存
                    holder.setText(R.id.tv_kucun, data.getTotal());
                    if ("0".equals(data.getTotal())) {
                        holder.getView(R.id.img_sold_out).setVisibility(View.VISIBLE);
                    }
                    //价格
                    if (data.getBegin_price().equals(data.getEnd_price())) {
                        holder.getView(R.id.ll_endprice).setVisibility(View.GONE);
                        if (ASUtils.isCanUse(data.getMarketprice())) {
                            holder.setText(R.id.tv_price, data.getMarketprice());
                        }
                    } else {
                        holder.getView(R.id.ll_endprice).setVisibility(View.VISIBLE);
                        if (ASUtils.isCanUse(data.getBegin_price())) {
                            holder.setText(R.id.tv_price, data.getBegin_price());
                        }
                        if (ASUtils.isCanUse(data.getEnd_price())) {
                            holder.setText(R.id.tv_endprice, data.getEnd_price());
                        }
                    }
                    //图片
                    if (ASUtils.isCanUse(data.getThumb())) {
                        Picasso.with(MyApp.context).load(data.getThumb()).placeholder( R.mipmap.zhanweitu).into(holder.getImageView(R.id.img_home));
                    }
               /*     if ("1".equals(data.getIsagentgoods())) {                             //店长专区
                        holder.getView(R.id.ll_lirun).setVisibility(View.VISIBLE);
                 //       holder.getView(R.id.tv_lijian).setVisibility(View.GONE);
                 //       holder.getView(R.id.tv_lijian2).setVisibility(View.GONE);
                      //  holder.getView(R.id.tv_profit).setVisibility(View.GONE);

                        holder.getView(R.id.ll_zaisou).setVisibility(View.GONE);
                        holder.getView(R.id.iv_add_dianpu).setVisibility(View.GONE);
                        holder.getView(R.id.iv_add_image).setVisibility(View.GONE);
                        holder.getView(R.id.iv_fenxiang).setVisibility(View.GONE);
                    } else {                                                              //非店主专区
                        holder.getView(R.id.ll_lirun).setVisibility(View.GONE);
                        holder.getView(R.id.ll_zaisou).setVisibility(View.VISIBLE);
                        holder.getView(R.id.iv_add_dianpu).setVisibility(View.VISIBLE);
                        holder.getView(R.id.iv_add_image).setVisibility(View.VISIBLE);
                        holder.getView(R.id.iv_fenxiang).setVisibility(View.VISIBLE);


                    }
*/

                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setOnItemClickListener(new CommonHeadAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                canByModel.getData(res.get(position).getId(), GroupDayActivity.this);
                GroupDayActivity.this.position = position;
            }
        });

    }

    /**
     * 展示分享的popupwindow
     */
    private void showSharePopupwindow(final GoodsBean data) {
        //设置contentView
        View contentView = LayoutInflater.from(GroupDayActivity.this).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (data != null) {
            tvprice.setText(NumberUtils.DecimalFormat(data.getProfit()));
            tvpricetwo.setText(NumberUtils.DecimalFormat(data.getProfit()));
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, LIANJIE, GroupDayActivity.this);
                    } else {
                        ShareUtils.copyLianjie(GroupDayActivity.this, wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, ERWEIMA, GroupDayActivity.this);
                    } else {
                        ShareUtils.ereima3(GroupDayActivity.this, data.getTitle(), data.getMarketprice(), null, null, null, data.getThumb(), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, WEIXINHAOYOU, GroupDayActivity.this);
                    } else {
                        ShareUtils.wxshare(data.getTitle(), data.getImages().get(0), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, PENGYOUQUAN, GroupDayActivity.this);
                    } else {
                        ShareUtils.wxPengyouquan(data.getTitle(), data.getThumb(), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void getDataError(Object object) {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void AddDianpuSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "上架成功", jsonObject.optString("res"));
//        ToastUtils.makeToastShort("添加到店铺成功");
        if ("0".equals(icon)) {
            res.get(positon).setIcon("1");
        } else {
            res.get(positon).setIcon("0");
        }
        adapter.notifyItemChanged(positon);
    }

    @Override
    public void AddDianpuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void deleteSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "下架成功", jsonObject.optString("res"));
        if ("0".equals(icon)) {
            res.get(positon).setIcon("1");
        } else {
            res.get(positon).setIcon("0");
        }
        adapter.notifyItemChanged(positon);
    }

    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onRefresh() {
        page = 1;
        LoadingDialogUtils.showProgress(GroupDayActivity.this, "正在加载,请稍后~");
        model.getDataforID(id, page + "", GroupDayActivity.this);
    }

    @Override
    public void getCanBuySuccess(Object object) {
        Intent intent = null;
        if ("1".equals(res.get(position).getIsagentgoods())) {
            intent = new Intent(this, CommodityDetails_DZZQActivity.class);
        } else {
          intent = new Intent(this, CommodityDetailsActivity.class);
        }
        intent.putExtra("id", res.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void getCanBuyError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(this, wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima3(this, res.get(positon).getTitle(), res.get(positon).getMarketprice(), null, null, null, res.get(positon).getThumb(), wxURL);
        } else if (num == WEIXINHAOYOU) {
            ShareUtils.wxshare(res.get(positon).getTitle(), res.get(positon).getImages().get(0), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(res.get(positon).getTitle(), res.get(positon).getThumb(), wxURL);
        }
    }

    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
